var getId = "root", getName = "";
$(function() {
	// ajax全局设置
	if(isAdmin){
		$('#btnSyncContacts').show();
	}else{
		$('#btnSyncContacts').hide();
	}
	$.ajaxSetup({
		beforeSend : function(request) {
			request.setRequestHeader("X-AIRPORT-TOKEN", localStorage
					.getItem("oauth_token"));
		}
	})
	$('.table-sort').dataTable(pageStting());
	$("#specialEmployee").height(window.screen.availHeight - 210 + "px");
	var specialEmployee = function() {
		$.ajax({
			url : baseURL + '/services/dept/listDept',
			type : 'get',
			dataType : 'JSON',
			contentType : '',
			success : function(result) {
				if (result.errorcode == "1") {
					layer.msg("查询失败！");
					return;
				}
				if (result.errorcode == "0") {
					if (result.results == null) {
						layer.msg('没有数据')
						return false;
					}
					var html = "";
					var obj = result.results;
					function returnBack(obj) {
						if (!obj)
							return;
						$.each(obj, function() {
							if (this.subDepartmentList != null
									&& this.subDepartmentList != "[]"
									&& this.subDepartmentList.length != 0) {
								html += "<li><span class='folder' id='"
										+ this.id + "'>" + this.name
										+ "</span><ul>";
								returnBack(this.subDepartmentList)
								html += "</ul>";
							} else {
								html += "<li><span class='file' id='" + this.id
										+ "'>" + this.name + "</span>";
							}
						})
						html += "</li>";
					}
					returnBack(obj)
					$("#specialEmployee").append(html)
				}
				$("#specialEmployee").treeview({
					animated : "fast",
					collapsed : true,
					unique : true,
					// persist: "cookie",
					toggle : function() {
						// window.console && console.log("%o was toggled",
						// this);
					}
				})
				$("#specialEmployee").find('span').on('click', function(e) {
					e.stopPropagation();
					getId = $(e.target).attr('id');
					getName = $.trim($("#searchTemplet").val())
					$('.table-sort').DataTable().search({}).draw();
				})
				$('#searchName').click(function() {
					getName = $.trim($("#searchTemplet").val())
					$('.table-sort').DataTable().search({}).draw();
				})
			}
		})
	}
	specialEmployee();
	$(window).resize(function() {
		$(".table-sort").css('width', '100%');
	});
	var syncContacts = function() {
		$.ajax({
			url : baseURL + '/api/contacts/manualSyncData',
			type : 'get',
			dataType : 'JSON',
			contentType : '',
			success : function(result) {
				if (result.errorcode == "1") {
					layer.msg("同步通讯录失败！");
					return;
				}
				if (result.errorcode == "0") {
					layer.msg('同步通讯录成功！');
				}
			}
		})
	}
	syncContacts();
	// 强制更新通讯录数据
	$("#btnSyncContacts").on('click', function() {
		syncContacts();
	});
	// 定时刷新
	$("#btn").on('click', function() {
		$("#specialEmployee").empty();
		specialEmployee();
	})
})
// 从服务器分批取数据
pageStting = function() {
	var optsortable = {
		"bPaginate" : true,
		"stateSave" : true,
		"bProcessing" : true,
		"iDisplayLength" : 10,
		"bLengthChange" : false,
		"sAjaxSource" : baseURL + '/services/dept/listEmployeeAndSub',
		"sPaginationType" : 'full_numbers',
		"bServerSide" : true,
		"bSort" : false,
		"bFilter" : false,
		"aoColumnDefs" : [ {
			"bVisible" : false,
			"aTargets" : [ 0 ]
		}, {
			"bVisible" : false,
			"aTargets" : [ 6 ]
		} ],
		"fnServerData" : function(sSource, aoData, fnCallback) {
			// sSource=baseURL+'/services/dept/listEmployeeAndSub?deptId='+getId+"&name="+getName;
			sSource = baseURL + '/services/dept/listEmployeeAndSub';
			var globalSearch = {};
			var searchConditions = {};
			searchConditions.deptId = getId;
			searchConditions.name = getName;
			globalSearch.name = 'globalSearch';
			globalSearch.value = JSON.stringify(searchConditions);
			aoData.push(globalSearch);
			$
					.ajax({
						type : "GET",
						url : sSource,
						dataType : "json",
						contentType : "application/json;charset=UTF-8",
						data : aoData, // 以json格式传递
						success : function(result) {
							if (result.errorcode == "1") {
								layer.msg('数据错误：' + result.message);
								return false;
							}
							if (result.errorcode == "0") {
								if (result.results == null) {
									result.results = [];
								}
								var obj = result;
								var data = result.results;
								var aaData = [];
								var dataResult = {};
								dataResult.iTotalRecords = obj.totalcount;
								dataResult.iTotalDisplayRecords = obj.totalcount;
								dataResult.iDisplayStart = obj.offset;
								dataResult.iDisplayLength = obj.limit;
								dataResult.aaData = aaData;
								// json重构数组对象
								$
										.each(
												data,
												function(i, val) {
													aaData[i] = []
													aaData[i].push(val.id);
													aaData[i]
															.push(val.empName != null ? val.empName
																	: "-");
													aaData[i]
															.push(val.belongDepartmentName != null ? val.belongDepartmentName
																	: val.departmentName != null ? val.departmentName
																			: "-");
													aaData[i]
															.push(val.positionName != null ? val.positionName
																	: "-");
													aaData[i]
															.push(val.empPhoneNo != null ? val.empPhoneNo
																	: "-");
													aaData[i]
															.push(val.empPhoneNo != null ? val.empPhoneNo
																	: "-");
													aaData[i].push(val.id);
													// aaData[i].push(val.null_n);
												});
								fnCallback(dataResult);
							}
						}
					});
		}
	}
	return optsortable;
}